﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Permissions;
using System.Web;
using System.Web.Http.Controllers;
using System.Web.Http.ModelBinding;

namespace NCS.IConnect.Core.WebApi
{
    /// <summary>
    /// A custom <see cref="IModelBinder"/> to bind version no specific parameter by extracting data from If-Match header.
    /// </summary>
    public class VersionNoModelBinder: IModelBinder
    {
        /// <summary>
        /// Binds the model to a value by using the specified controller context and binding context.
        /// </summary>
        /// <param name="actionContext">The action context.</param>
        /// <param name="bindingContext">The binding context.</param>
        /// <returns>true if model binding is successful; otherwise, false.</returns>
        [EnvironmentPermission(SecurityAction.LinkDemand, Unrestricted = true)]
        public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
        {
            if (!actionContext.Request.Headers.IfMatch.Any())
            {
                return false;
            }
            int versionNo;
            if (int.TryParse(actionContext.Request.Headers.IfMatch.First().Tag.Trim('"'), out versionNo))
            {
                bindingContext.Model = versionNo;
                return true;
            }
            return false;
        }
    }
}